// 服务器接口地址
import { baseURL } from '@/config'

// 验证登录情况
function ajaxFilter(data: any) {
	let status = true
	if (data.code == 'A0230') {
		status = false
		uni.showToast({
			title: '登录状态失效',
			icon: 'none'
		})
		uni.removeStorageSync('token')
		uni.reLaunch({
			url: '/pages/login/index',
		})
	}
	return status
}
function request(url: string, method: "GET" | "POST" | "DELETE" | "PUT" | undefined, data: object | any) {
	return new Promise(function (resolve, reject) {
		// uni.showLoading({
		// 	title: '加载中',
		// 	mask: true,
		// })
		let header: any
		const token = uni.getStorageSync('token')
		const token_type = uni.getStorageSync('token_type')
		if( url == '/zgyp-auth/user/login') {
			header = {
				'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
				'Authorization': 'Basic d3hhcHA6emd5cDY2Njg4OA==',
			}
		} else {
			if (token) {
				if(method=='GET'){
					header = {
						'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
						'Authorization': `${token_type} ` + `${token}`
					}
				} else {
					header = {
						'content-type': 'application/json',
						'Authorization': `${token_type} ` + `${token}`
					}
				}
			} else {
				if(method=='GET'){
					header = {
						'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
						'Authorization': 'Basic d3hhcHA6emd5cDY2Njg4OA==',
					}
				} else {
					header = {
						'content-type': 'application/json',
						'Authorization': 'Basic d3hhcHA6emd5cDY2Njg4OA=='
					}
				}
			}
		}
	
		uni.request({
			url: baseURL + url,
			method: method,
			data: data,
			header: header,
			success(res: any) {
				uni.hideLoading()
				if (ajaxFilter(res.data) && res.statusCode == 200) {
					resolve(res.data)
				} else if (res.statusCode != 401) {
					//其他异常
					uni.showToast({
						title: res.data.msg,
						icon: 'none'
					})
					reject(res.data)
				} else if (res.statusCode == 401) {
					if(url == '/zgyp-ums/app-api/v1/members/me'){
            return
					}else{
						uni.showToast({
							title: '登录状态失效',
							icon: 'none'
						})
						uni.removeStorageSync('token')
					}
					// uni.reLaunch({
					// 	url: '/pages/login/index',
					// })
				}
			},
			fail(err) {
				uni.hideLoading()
				//请求失败
				uni.showToast({
					title: '无法连接到服务器',
					icon: 'none'
				})
				reject(err)
			}
		})
	})
}
export { request, baseURL }
